<script setup lang="ts">
defineOptions({
  name: "curve"
});
import { ref, nextTick, computed, onMounted, defineAsyncComponent } from "vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { queryDailyData } from "@/api/modules/operation";
import { useInitEchartsOptions } from "../hooks";
import dayjs from "dayjs";

const echartsCom = defineAsyncComponent(() => import("@/views/common/components/echartsCom/index.vue"));
const echartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);
const props = withDefaults(defineProps<{ title: string; unit: string; pointCode: string; groupCode: string; deviceCode: string; scale: number }>(), {
  title: "",
  unit: "",
  pointCode: "",
  groupCode: "",
  deviceCode: "",
  scale: 0
});
const echartsOptions = ref<Record<string, any>>(null);
const dialogVisible = defineModel({ type: Boolean, default: false });
const searchLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
let defaultParams = computed(() => ({ positionNum: props.pointCode, groupCode: props.groupCode, scale: props.scale }));
const currentParams = ref<Record<string, any>>({});
const searchOption = ref<Array<CommonSearch.SearchOption>>([
  {
    label: "日期范围",
    key: "startMeterReadingTime",
    realKeys: ["startMeterReadingTime", "endMeterReadingTime"],
    value: [dayjs().subtract(6, "day").startOf("day").format("YYYY-MM-DD HH:mm:ss"), dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss")],
    type: "daterange",
    props: {
      clearable: false
    },
    span: 10
  }
]);

const updateData = async (flag: boolean = false) => {
  // 调试
  // const groupCode = "BULK_GAS";
  // const positionNum = "BGMS_HPCDA_FLOW_PV";
  // const params = { ...defaultParams.value, ...currentParams.value, groupCode, positionNum };
  const params = { ...defaultParams.value, ...currentParams.value };
  await init(params, flag);
};

const submitSearchFormHandler = async (form: any, flag: boolean = false) => {
  currentParams.value = { ...currentParams.value, ...form };
  await updateData(flag);
};

const resetSearchFormHandler = async (form: any) => {
  currentParams.value = { ...currentParams.value, ...form };
  await updateData(false);
};

const initEcharts = async (flag: boolean = false, list: Array<any>) => {
  if (!list?.length) {
    echartsOptions.value = null;
    await nextTick();
    !flag && (await echartsComRef.value?.updateOption(true));
    return;
  }
  echartsOptions.value = useInitEchartsOptions(
    list,
    `${props.deviceCode}${props.title}${props.unit ? "（" + props.unit + "）" : ""}`,
    props.unit,
    props.scale
  );
  await nextTick();
  !flag && (await echartsComRef.value?.updateOption(true));
};

const init = async (params: Record<string, any>, flag: boolean = false) => {
  loading.value = true;
  const res = await queryDailyData(params, () => {
    loading.value = false;
  });
  await initEcharts(flag, res);
  await nextTick();
  loading.value = false;
};
</script>

<template>
  <px-dialog v-model="dialogVisible" :title="`${title}曲线（${deviceCode}）`" width="80%">
    <div v-loading="searchLoading" class="dialog-content">
      <div class="dialog-search">
        <commonSearch
          v-if="searchOption?.length"
          ref="commonSearchRef"
          v-model:loading="searchLoading"
          :row-num="2"
          :operation-span="3"
          :option="searchOption"
          @submit="submitSearchFormHandler"
          @reset="resetSearchFormHandler"
        />
      </div>
      <div v-loading="loading" class="dialog-curve">
        <Suspense>
          <template #fallback>
            <div v-loading="true" class="echarts-fallback" />
          </template>
          <template #default>
            <div class="echarts-default">
              <echartsCom ref="echartsComRef" :options="echartsOptions" />
            </div>
          </template>
        </Suspense>
      </div>
    </div>
    <template #footer>
      <px-button type="primary" @click="dialogVisible = false"> 关闭 </px-button>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
.dialog-curve {
  width: 100%;
  height: 400px;
  margin-top: 16px;
  border: 1px solid #eee;

  .echarts-fallback {
    width: 100%;
    height: 100%;
  }

  .echarts-default {
    width: 100%;
    height: 100%;
  }
}
</style>
